package com.example.CarFee;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.trainfee.R;
import com.navdrawer.SimpleSideDrawer;

public class MainActivity extends Activity {
	private ImageView menuBtn;
	private SimpleSideDrawer sideMenu;
	private ListView sideMenu_listview;
	private SimpleAdapter adapter;
	private List<Map<String, String>> items;
	private String[] item_msg = { "个人信息", "我的订单", "讨论专区", "应用说明", "关于我们", "退出登录" };
	private Spinner startPlace, destination;
	private String[] placeArray = { "广州", "深圳", "信宜", "汕尾", "汕头", "潮州", "揭阳",
			"梅州", "阳江" };
	private ArrayAdapter placeAdapter;
	private Button checkBtn;
	private TextView date, time, station;
	private DatePicker datePicker;
	private boolean isDateShow = false, isTimeShow = false;
	private String[] stationItem = new String[] { "天河客运站", "广园客运站", "广州火车东站" };
	private String[] timeItem = new String[] { "0:00", "1:00", "2:00", "3:00",
			"4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00",
			"12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00",
			"19:00", "20:00", "21:00", "22:00", "23:00", "24:00", };
	private boolean isShow = false;
	private ProgressDialog bar;
	private int fee;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sideMenu = new SimpleSideDrawer(this);
		sideMenu.setLeftBehindContentView(R.layout.sidemenu);
		menuBtn = (ImageView) findViewById(R.id.menuBtn);
		sideMenu_listview = (ListView) sideMenu.findViewById(R.id.listView);
		startPlace = (Spinner) findViewById(R.id.spinner1);
		destination = (Spinner) findViewById(R.id.spinner2);
		datePicker = (DatePicker) findViewById(R.id.datePicker);
		placeAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_checked, placeArray);
		startPlace.setAdapter(placeAdapter);
		destination.setAdapter(placeAdapter);
		date = (TextView) findViewById(R.id.date);
		date.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
		time = (TextView) findViewById(R.id.time);
		time.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
		station = (TextView) findViewById(R.id.station);
		station.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); // 下划线
		checkBtn = (Button) findViewById(R.id.checkBtn);
		items = new ArrayList<Map<String, String>>();
		for (int i = 0; i < item_msg.length; i++) {
			HashMap<String, String> item = new HashMap<String, String>();
			item.put("text", item_msg[i]);
			items.add(item);
		}
		adapter = new SimpleAdapter(this, items,
				R.layout.sidemenu_listview_item, new String[] { "text" },
				new int[] { R.id.text });
		sideMenu_listview.setAdapter(adapter);
		bar = new ProgressDialog(this);
		bar.setTitle("查询中");
		bar.setMessage("查询中");
		
		sideMenu_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if (position == 1) {
					Intent intent = new Intent(MainActivity.this,
							RecordAcitvity.class);
					startActivity(intent);
				}
				if (position == 0) {
					Intent intent = new Intent(MainActivity.this,
							InfoActivity.class);
					startActivity(intent);
				}
				if (position == 2) {
					Intent intent = new Intent(MainActivity.this,
							DiscussActivity.class);
					startActivity(intent);
				}
				if (position == 5) {
					finish();
				}
			}
		});
		menuBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sideMenu.toggleLeftDrawer();
			}
		});
		
		checkBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (destination.getSelectedItem().toString() == startPlace
						.getSelectedItem().toString()) {
					Toast.makeText(MainActivity.this, "地点相同，不能订票",
							Toast.LENGTH_SHORT).show();
				} else {
					Thread thread = new Thread(new Runnable() {
						
						@Override
						public void run() {
							String a = "";
							String b = "";
							try {
								a = URLEncoder.encode(startPlace.getSelectedItem()
										.toString(), "UTF-8");
								b = URLEncoder.encode(destination.getSelectedItem()
										.toString(), "UTF-8");
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
							fee = Service.CheckRemainTicket(a, b);
							handler.sendEmptyMessage(0x120);
						}
					});
					thread.start();
					bar.show();
				}
			}
		});
		time.setText("9:00");
		date.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (isDateShow) {
					datePicker.setVisibility(View.GONE);
					isDateShow = false;
				} else {
					datePicker.setVisibility(View.VISIBLE);
					isDateShow = true;
				}
			}
		});
		station.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this).setTitle("选择出发时间").setItems(
						stationItem, new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int pos) {
								station.setText(stationItem[pos]);
							}

						});
				builder.create().show();
			}
		});
		time.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this).setTitle("选择站点").setItems(timeItem,
						new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface arg0, int pos) {
								time.setText(timeItem[pos]);
							}
							
						});
				builder.create().show();
			}
		});
		initTime();
	}

	public void initTime() {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR);
		int minute = c.get(Calendar.MINUTE);
		datePicker.init(year, month, day, new OnDateChangedListener() {

			@Override
			public void onDateChanged(DatePicker arg0, int year, int month,
					int day) {
				month++;
				if (month < 10 && day < 10) {
					date.setText(year + "-0" + month + "-0" + day);
				}
				if (month >= 10 && day < 10) {
					date.setText(year + "-" + month + "-0" + day);
				}
				if (month < 10 && day >= 10) {
					date.setText(year + "-0" + month + "-" + day);
				}
				if (month >= 10 && day >= 10) {
					date.setText(year + "-" + month + "-" + day);
				}
			}
		});
	}
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			bar.cancel();
			if (msg.what == 0x120) {
				Toast.makeText(MainActivity.this, "余票数为" + fee,
						Toast.LENGTH_SHORT).show();
				bar.cancel();
				if (fee > 0) {
					Intent intent = new Intent(MainActivity.this,
							BuyActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("start", startPlace.getSelectedItem()
							.toString());
					bundle.putString("end", destination.getSelectedItem()
							.toString());
					bundle.putString("date", date.getText().toString());
					bundle.putString("time", time.getText().toString());
					bundle.putString("station", station.getText()
							.toString());
					intent.putExtras(bundle);
					startActivity(intent);
				}
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.KEYCODE_BACK) {
			System.exit(0);
		}
		return super.onKeyDown(keyCode, event);
	}

}
